//
//  NewOrderViewController.m
//  BaishidaiShop
//
//  Created by mac book on 2019/1/18.
//  Copyright © 2019年 sy. All rights reserved.
//

#import "NewOrderViewController.h"
#import "LoginViewController.h"


#import "NewOrderTableViewCell.h"
#import "NewOrderHeaderView.h"
#import "NewOrderFooterView.h"

#import "CustomAlertView.h"


#define  GoodsCell_H  60
#define  HeaderView_H  230




@interface NewOrderViewController ()<DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,UITableViewDelegate,UITableViewDataSource,OrderFooterDelegate,OrderHeaderDelegate>

@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSMutableArray* arrayData;

@property(nonatomic,strong) Pager* page;
@property(nonatomic,strong) NSString* cellIdentifier;
@property(nonatomic,strong) NSString* headerIdentifier;
@property(nonatomic,strong) NSString* footerIdentitifer;

@property(nonatomic,strong) OrderModel * currentOrder;


@end

@implementation NewOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  
    self.navigationItem.title = @"佰食袋商户";
    self.cellIdentifier = @"OrderCell";
    self.headerIdentifier = @"OrderHeader";
    self.footerIdentitifer = @"OrderFooter";
    
    
    [self setUpSubViews];
    
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadData:) name:NotificationRemoteAt object:nil];
    
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self refreshDataSource];
}

-(void)setUpSubViews{
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    
    
    
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    
    [self.tableView registerClass:[NewOrderTableViewCell class] forCellReuseIdentifier:self.cellIdentifier];
    [self.tableView registerClass:[NewOrderHeaderView class] forHeaderFooterViewReuseIdentifier:self.headerIdentifier];
    [self.tableView registerClass:[NewOrderFooterView class] forHeaderFooterViewReuseIdentifier:self.footerIdentitifer];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
}

#pragma mark -  Data source
-(void)getData{
    
    NSDictionary* arg = @{
                          @"ince":@"get_neworder_list",
                          @"sid":[UserHandle shareInstance].userId
                          };

      [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
          
          NSLog(@"data = %@",data);
          [self.arrayData removeAllObjects];
          NSInteger flag = [[data objectForKey:@"ret"]integerValue];
          if(flag == 200){
              NSArray* array = [data objectForKey:@"data"];
              
              self.arrayData = [OrderModel mj_objectArrayWithKeyValuesArray:array];

              [self.tableView reloadData];
          }else{
              [self alertHUD:[data objectForKey:@"msg"]];
          }
          [self.tableView.mj_header endRefreshing];
          
      } failure:^(NSError *error) {
          [self alertHUD:@"网络异常"];
          [self.tableView.mj_header endRefreshing];
          NSLog(@"%@",error);
      }];
    
}

-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //WJ
        [weakSelf getData];
    }];
    
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - UITableView

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.arrayData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
    OrderModel* orderModel = self.arrayData[indexPath.section];
    cell.arrayGoods = orderModel.items;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    OrderModel* orderModel =self.arrayData[indexPath.section];
    return orderModel.items.count * GoodsCell_H;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return  HeaderView_H;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 190.f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    NewOrderHeaderView *headerView = [[NewOrderHeaderView alloc]init];
    headerView.delegate = self;
    [headerView loadData:self.arrayData[section] index:section+1];
    return headerView;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    OrderModel* model = self.arrayData[section];
    
    NewOrderFooterView *footerView = [[NewOrderFooterView alloc]init];
    footerView.orderModel = model;
    footerView.delegate = self;
    return footerView;
}

#pragma mark - <OrderFooterDeleagte>
#pragma mark - 商家取消订单
-(void)orderFooterCancel:(OrderModel *)orderModel{//商家取消订单
    self.currentOrder = orderModel;
    
    CustomAlertView *alertView = [[CustomAlertView alloc] initTextViewAlert];
    alertView.textBlock = ^(NSString *textStr) {
        NSLog(@"textStr = %@",textStr);
        [self showHUD];
        NSDictionary* arg = @{@"ince":@"cancel_shop_order",
                              @"sid":[UserHandle shareInstance].userId,
                              @"order_id":self.currentOrder.order_id,
                              @"cancel_res":textStr
                              };
        
        [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
            NSLog(@"data = %@",data);
            NSInteger flag = [[data objectForKey:@"ret"]integerValue];
            if(flag == 200){
                [self hidHUD:[data objectForKey:@"msg"]];
                [self.tableView.mj_header beginRefreshing];
            }else{
                [self hidHUD:[data objectForKey:@"msg"]];
            }
            
        } failure:^(NSError *error) {
            [self hidHUD:@"网络异常"];
        }];
        
    };
    
    [alertView showAlertView];
    
}

#pragma mark - 商家接单
-(void)orderFooterSend:(OrderModel *)orderModel{ //商家接单
    self.currentOrder = orderModel;
    [self showHUD];
    NSDictionary* arg = @{@"ince":@"confirm_shop_order",
                          @"sid":[UserHandle shareInstance].userId,
                          @"order_id":self.currentOrder.order_id
                          };

    
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        NSLog(@"data = %@",data);
        NSInteger flag = [[data objectForKey:@"ret"]integerValue];
        if(flag == 200){
            [self hidHUD:[data objectForKey:@"msg"]];
            [self.tableView.mj_header beginRefreshing];
        }else{
            [self hidHUD:[data objectForKey:@"msg"]];
        }
        
    } failure:^(NSError *error) {
        [self hidHUD:@"网络异常"];
    }];
    
}

#pragma mark - 打电话
-(void)callDelivery:(NSString *)phone{
    
    NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",phone];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
}

-(void)orderHeaderPhoneCall:(OrderModel *)orderModel{
    
    NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",orderModel.phone];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
    
}


#pragma mark - DZEmptyData 协议实现
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc] initWithString:@"暂无新订单" attributes:@{NSFontAttributeName :[UIFont boldSystemFontOfSize:17.0],NSForegroundColorAttributeName:[UIColor grayColor]}];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return roundf(self.tableView.frame.size.height/10.0);
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

#pragma mark - 通知
-(void)reloadData:(NSNotification*)notification{
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - 懒加载
-(NSMutableArray *)arrayData{
    if(!_arrayData){
        _arrayData = [[NSMutableArray alloc]init];
    }
    return _arrayData;
}






/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
